#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- This's Excel Util
# --
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Email lmay@lmaye.com
# Date: 2018/5/2 16:56 星期三
# ----------------------------------------------------------
import csv
import xlwt
from core.constant.sys_enum import SysEnum
from core import LOG


def write_data_to_excel(out_path, file_name, data, file_suffix=".xls"):
    """
        write data to excel

        :param out_path: 保存路径
        :param file_name: 文件名
        :param data: 数据
        :param file_suffix: 文件后缀
        :return:
    """
    # 实例化一个Workbook()对象(即excel文件)
    wbk = xlwt.Workbook()
    # 新建一个名为Sheet1的excel sheet。此处的cell_overwrite_ok =True是为了能对同一个单元格重复操作。
    sheet = wbk.add_sheet('Sheet1', cell_overwrite_ok=True)
    # 遍历result中的没个元素。
    for i in range(len(data)):
        # 对result的每个子元素作遍历，
        for j in range(len(data[i])):
            # 将每一行的每个元素按行号i,列号j,写入到excel中。
            sheet.write(i, j, data[i][j])
    # 保存
    wbk.save(out_path + file_name + file_suffix)


def write_data_to_csv(out_path, file_name, data):
    """
        write data to CSV

        解决文件格式: 指定换行符生成Unix格式文件
        writer = csv.writer(csv_file, lineterminator="\\n")

        :param out_path: 保存路径
        :param file_name: 文件名
        :param data: 数据
        :return:
    """
    try:
        with open(out_path + SysEnum.SEPARATOR.value + file_name, "w", encoding="UTF-8", newline="\n") as csv_file:
            writer = csv.writer(csv_file, lineterminator="\n")
            writer.writerows(data)
            csv_file.close()
    except Exception as e:
        LOG.error(e)
